<?php
namespace App\DBs;

use Illuminate\Support\Facades\DB;

class OpinionDB extends BaseDB
{
    /**
     * 用户建议
     * uid 用户UID
     * detail 手机号码
     * level 建议等级
     */

    protected $table = 'user_opinion';

    public function __construct()
    {
    }

    //列表
    public function getIndex($uid)
    {
        $query = DB::table($this->table);
        if ($uid) { $query = $query->where('uid',$uid); }
        $models = $query->orderBy('id','desc')
            ->skip(0)
            ->take(50)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $items[] = [
                'uid' => $model['uid'],
                'detail' => $model['detail'],
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$items);
    }

    //新增
    public function setAdd($uid,$detail)
    {
        if (!$uid || !$detail) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->table)
                ->insertGetId([
                    'uid' => $uid,
                    'detail' => $detail,
                    'level' => 1,
                    'created_at' => time(),
                ]);
            $dataArr = array(
                'lastId' => $lastId,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}